import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getToken } from '@/utils/auth';
import { useUserStoreHook } from '@/store/modules/user';

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (!config.headers) {
      throw new Error(
        `Expected 'config' and 'config.headers' not to be undefined`
      );
    }
    const user = useUserStoreHook();
    if (user.token) {
      (config.headers as any).Authorization = getToken();
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { status, msg } = response.data;
    if (status === 200) {
      return response.data;
    } else {
      // 响应数据为二进制流处理(Excel导出)
      if (response.data instanceof ArrayBuffer) {
        return response;
      }

      ElMessage({
        message: msg || '系统出错',
        type: 'error'
      });
      return Promise.reject(new Error(msg || 'Error'));
    }
  },
  (error: any) => {
    let message = ''
    // 错误的请求结果处理，这里的代码根据后台的状态码来决定错误的输出信息
    if (error && error.response) {
      switch (error.response.status) {
        case 400: {
          message = '错误请求'
          if (error.response.data) {
            if (error.response.data.error === 'invalid_grant') {
              message = '登录失败'
              if (error.response.data.error_description === 'Bad credentials') {
                message = '用户名或密码错误'
              }
            } else if (error.response.data.error === 'access_denied') {
              message = '禁止登录'
              if (error.response.data.error_description === 'user role not found!') {
                message = '用户角色不存在'
              }
            }
          }
          break
        }
        case 401: {
          // common.cookies.clear()
          message = '未授权，请重新登录'
          if (error.response.data) {
            if (error.response.data.error === 'invalid_grant') {
              if (error.response.data.error_description === 'Bad credentials') {
                message = '登录参数有误'
              }
            } else if (error.response.data.error === 'unauthorized') {
            }
          }
          break
        }
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求错误,未找到该资源'
          break
        case 405:
          message = '请求方法未允许'
          break
        case 408:
          message = '请求超时'
          break
        case 500:
          message = '服务器端出错'
          break
        case 501:
          message = '网络未实现'
          break
        case 502:
          message = '网络错误'
          break
        case 503:
          message = '服务不可用'
          break
        case 504:
          message = '网络超时'
          break
        case 505:
          message = 'http版本不支持该请求'
          break
        default:
          message = `连接错误${error.response.status}`
      }
    } else {
      message = '连接到服务器失败'
    }
    return Promise.reject(message)
  }
);

// 导出 axios 实例
export default service;
